<?php
	/**
	* microtime_float
	* this function is for getting the time in a format we can use for working
	* out how long a page takes to generate
	*
	* @return float
	*/
	function microtime_float()
	{
		list($usec, $sec) = explode(' ', microtime());
		return ((float)$usec + (float)$sec);
	}

	/**
	* debug
	* display the print_r output of $var in pre tags. If the second argument is
	* true then strip all leading space from the start of each line
	*
	* @param mixed $var the var to print
	*
	* @return void
	*/
	function debug($var,$die=false)
	{
		echo "\n<pre>\n";
		if (is_string($var)) {
			$var = preg_replace("%\n[\t\ \n\r]+%", "\n", $var);
		} elseif (is_bool($var)) {
			var_dump($var);
		} else {
			print_r($var);
		}
		echo "\n</pre>\n";

		if ($die) {	die(); }
	}

	function checkCache() {
		define('LASTMOD_FORMAT', 'D, d M Y H:i:s \G\M\T');

		if (headers_sent()) {
			return;
		}

		session_cache_limiter("private");

		//Get the last modification date
		$site_lastmod = filemtime("admin/includes/config.php");
		$lastmod = strtotime("1970-01-01 00:00:00");

		if ($site_lastmod > $lastmod) {
			$lastmod = $site_lastmod;
		}

		if ((isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) && ($lastmod <= strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']))) {
			header("HTTP/1.0 304 Not Modified");
			die();
		}

		header('Last-Modified: '.date(LASTMOD_FORMAT, $lastmod));
	}

	$start_time = microtime_float();

	error_reporting(E_ALL);
	set_magic_quotes_runtime(false);
	ini_set('track_errors','1');
	if (version_compare(PHP_VERSION, '4.3.0', '>=')) {
		ini_set('auto_detect_line_endings', true);
	}
	ob_start();

	// Setup the REQUEST_URI on IIS servers using ISAPI_Rewrite
	if (isset($_SERVER['HTTP_X_REWRITE_URL'])) {
		$_SERVER['REQUEST_URI'] = $_SERVER['HTTP_X_REWRITE_URL'];
	}

	if (!isset($_SERVER['REQUEST_URI']) || $_SERVER['REQUEST_URI'] == '') {
		$_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME'].'?'.(isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : '');
	}

	// Set our default system settings
	$GLOBALS['HideIntro'] = 'none';
	$GLOBALS['imagePath'] = dirname(__FILE__).'/images';
	
	$GLOBALS['CurrentYear'] = date('Y', time());

	define('PRODUCT_ID', 'IKM');

	// The minimum version of PHP required to run Interspire Knowledge Manager
	define("PHP_VERSION_REQUIRED", "4.3.0");
	define("PHP_VERSION_INSTALL_REQUIRED", "5.0.0");

	// The minimum version of MySQL required to run Interspire Knowledge Manager
	define("MYSQL_VERSION_REQUIRED", "4.1.0");

	//This is checked by the upgrade. It should be the last database upgrade junction point
	//for the current install
	define('VERSION', 'IKM5.1.1');

	define('VERSION_NUMBER','5.1.1'); //The actual displayed version number
	define('AKB_XML_SEARCH_WORD',1);
	define('AKB_XML_SEARCH_PHRASE',	2);
	define('MSG_ERROR',			0);
	define('MSG_SUCCESS',		1);
	define('MSG_WARNING',		2);
	define('MSG_INFORMATION',	3);
	
	define('WF_STATUS_APPROVED','approved');
	define('WF_STATUS_AUTO_APPROVED','auto_approved');
	define('WF_STATUS_PENDING','pending');
	define('WF_STATUS_REPENDING','re_pending');
	define('WF_STATUS_DISAPPROVED','disapproved');
	
	// define the max table name, to enable the sequence happening for Oracle, this is not include the prefix.
	define('MAX_TBL_LEN', 19);
	
	// How many results per page to display by default
	define('RESULTS_PER_PAGE', 20);
	define('AKB_QUEST_PER_PAGE',		RESULTS_PER_PAGE);
	define('AKB_NEWS_PER_PAGE',			RESULTS_PER_PAGE);
	define('AKB_GLOSSARY_PER_PAGE',		RESULTS_PER_PAGE);
	define('AKB_USER_PER_PAGE',			RESULTS_PER_PAGE);
	define('AKB_GROUP_PER_PAGE',		RESULTS_PER_PAGE);
	define('AKB_SUBSCRIBER_PER_PAGE',	RESULTS_PER_PAGE);
	define('AKB_COMMENT_PER_PAGE',		RESULTS_PER_PAGE);
	define('AKB_RATING_PER_PAGE',		RESULTS_PER_PAGE);
	define('AKB_QUESTION_PER_PAGE',		RESULTS_PER_PAGE);

	define('AKB_STAT_PAGE_ROWS',		20);

	define('MAX_COMMENT_LENGTH', 50);
	define('CAPTCHA_LENGTH', 6);
	define('SUBSCRIBER_EMAIL_THRESHOLD', 50);
	define('KEYWORD_MODE_WORD_MIN_LENGTH', 3);

	// How many items to show on the stats page in the control panel
	define('STATS_DEFAULT_NUM', 5);
	define('STATS_DEFAULT_FULL_NUM', 20);
	define('STATS_NUM_MOST_VIEWED_QUESTIONS',			STATS_DEFAULT_NUM);
	define('STATS_NUM_MOST_VIEWED_QUESTIONS_FULL',		STATS_DEFAULT_FULL_NUM);
	define('STATS_NUM_MOST_POPULAR_QUESTIONS',			STATS_DEFAULT_NUM);
	define('STATS_NUM_MOST_POPULAR_QUESTIONS_FULL',		STATS_DEFAULT_FULL_NUM);
	define('STATS_NUM_LEAST_POPULAR_QUESTIONS_FULL',	STATS_DEFAULT_FULL_NUM);
	define('STATS_NUM_MOST_POPULAR_CATEGORIES',			STATS_DEFAULT_NUM);
	define('STATS_NUM_MOST_EMAILED_QUESTIONS',			STATS_DEFAULT_NUM);
	define('STATS_NUM_MOST_POPULAR_AUTHORS',			STATS_DEFAULT_NUM);
	define('STATS_NUM_MOST_POPULAR_SEARCHES',			STATS_DEFAULT_NUM);
	define('STATS_NUM_MOST_POPULAR_SEARCHES_FULL',		STATS_DEFAULT_NUM);
	define('STATS_NUM_MOST_POPULAR_FAILED_SEARCHES_FULL',STATS_DEFAULT_NUM);
	define('STATS_NUM_MOST_POPULAR_FAILED_SEARCHES',	STATS_DEFAULT_NUM);
	define('STATS_NUM_HIGHEST_RATED_QUESTIONS',			STATS_DEFAULT_NUM);
	define('STATS_NUM_LOWEST_RATED_QUESTIONS',			STATS_DEFAULT_NUM);
	define('STATS_NUM_MOST_DISCUSSED_QUESTIONS_FULL',	STATS_DEFAULT_FULL_NUM);
	define('STATS_NUM_HIGHEST_RATED_QUESTIONS_FULL',	STATS_DEFAULT_FULL_NUM);
	define('STATS_NUM_MOST_POPULAR_AUTHORS_FULL',		STATS_DEFAULT_FULL_NUM);
	define('STATS_NUM_MOST_COMMENTS_FULL',				STATS_DEFAULT_FULL_NUM);
	define('STATS_NUM_MOST_POPULAR_CATEGORIES_FULL',	STATS_DEFAULT_FULL_NUM);

	define('SCORE_MODIFIER',							5);

	define('DEFAULT_POPULAR',							20);
	define('DEFAULT_RECENT',							10);
	define('DEFAULT_FEATURED',							10);
	define('DEFAULT_NEWS',								10);

	define('CF_TYPE__MULTI_CHECK','multi_check');
	define('CF_TYPE__FREE_FORM','freeform');

	// / on linux or \ on windows
	define('DS', DIRECTORY_SEPARATOR);

	// The filesystem root of IKM
	define('AKB_ROOT', dirname(__FILE__));

	// The directory the API files are in
	define('AKB_API', AKB_ROOT.DS.'lib'.DS.'api');

	// The size of the chunks to export - this keeps memory usage down
	define('EXPORT_CHUNKSIZE', 2048 * 1024);

	// cache path
	define('CACHE_PATH', AKB_ROOT.DS.'admin'.DS.'tmp');
	
	define('ATTACHMENT_DIR', AKB_ROOT.DS.'attachments');
	define('BACKUP_DIR', AKB_ROOT.DS.'attachments'.DS.'backups');

	// In the categories grid, how many do we display per row ?
	define('CATEGORIES_PER_ROW', 3);

	// The type of approval
	define('CATEGORIES_NO_APPROVAL', 0);
	define('CATEGORIES_ALWAYS_APPROVAL', 1);
	define('CATEGORIES_ONCE_APPROVAL', 2);
	
	// Valid folder length for doc plugin
	define('TEMP_DIR_LEN', 8);
	
	// Include our config
	if (file_exists(AKB_ROOT.DS.'admin'.DS.'includes'.DS.'config.php')) {
		require_once(AKB_ROOT.DS.'admin'.DS.'includes'.DS.'config.php');
	} else {
		die("You don't have a config file. Please create one to use The Knowledge Manager.");
	}

	/* System settings that depend on the config settings
	 * On php > 5.1.0, if the php.ini has't been setup with a default timezone
	 * you may have to uncomment the line below and set it manually otherwise
	 * it will complain about the timezone not being set. You can also set the
	 * php.ini setting date.timezone for a system wide fix for this
	 */
	// date_default_timezone_set('Australia/Sydney');

	// Include our generic files
	require(AKB_ROOT.DS.'lib'.DS.'general.php');
	require(AKB_ROOT.DS.'lib'.DS.'Cache.php');
	require(AKB_ROOT.DS.'lib'.DS.'tree.php');
	require(AKB_ROOT.DS.'lib'.DS.'database'.DS.'mysql.php');
	require(AKB_ROOT.DS.'lib'.DS.'database'.DS.'mssql.php');
	require(AKB_ROOT.DS.'lib'.DS.'database'.DS.'oci8.php');
	require(AKB_ROOT.DS.'lib'.DS.'ldap'.DS.'LdapFactory.php');
	require(AKB_ROOT.DS.'lib'.DS.'search'.DS.'_plugin.php');
	require(AKB_ROOT.DS.'lib'.DS.'search'.DS.'default.php');
	require(AKB_ROOT.DS.'lib'.DS.'search'.DS.'docx.php');
	require(AKB_ROOT.DS.'lib'.DS.'search'.DS.'external_doc.php');
	require(AKB_ROOT.DS.'lib'.DS.'search'.DS.'external_ppt.php');
	require(AKB_ROOT.DS.'lib'.DS.'search'.DS.'image.php');
	require(AKB_ROOT.DS.'lib'.DS.'search'.DS.'pdf.php');
	require_once(AKB_ROOT.DS.'lib'.DS.'multibyte.php');
	require(AKB_API.DS.'class.user.php');
	require(AKB_API.DS.'class.news.php');
	require(AKB_API.DS.'class.category.php');
	require(AKB_API.DS.'class.comment.php');
	require(AKB_API.DS.'class.question.php');
	require(AKB_API.DS.'class.rating.php');
	require(AKB_API.DS.'class.submittedquestion.php');
	require(AKB_API.DS.'class.subscriber.php');
	require(AKB_API.DS.'class.customfields.php');
	require(AKB_API.DS.'class.ldap.php');

	if ((isset($GLOBALS['isSetup']) && $GLOBALS['isSetup'] == true)) {
		$GLOBALS["faviconLink"] = $GLOBALS["pathToKB"].'/admin/images/favicon/favicon.ico';
		if ((isset($GLOBALS['databaseType']) && $GLOBALS['databaseType'] == 'mssql')) {
			$GLOBALS['AKB_DB'] = new MsSQLDb($GLOBALS['mySQLServer'], $GLOBALS['mySQLUser'], $GLOBALS['mySQLPass'], $GLOBALS['mySQLDatabase']);
			$GLOBALS['databaseVersion'] = array_shift(explode("\n", $GLOBALS['AKB_DB']->FetchOne("SELECT @@version")));
		} elseif ((isset($GLOBALS['databaseType']) && $GLOBALS['databaseType'] == 'oci8')) {
			$GLOBALS['AKB_DB'] = new Oci8Db($GLOBALS['mySQLServer'], $GLOBALS['mySQLUser'], $GLOBALS['mySQLPass'], $GLOBALS['mySQLDatabase']);
			$GLOBALS['databaseVersion'] = $GLOBALS['AKB_DB']->FetchOne("select * from V\$VERSION where banner like 'Oracle%'");
		} else {
			$GLOBALS['AKB_DB'] = new MySQLDb($GLOBALS['mySQLServer'], $GLOBALS['mySQLUser'], $GLOBALS['mySQLPass'], $GLOBALS['mySQLDatabase']);
			$GLOBALS['databaseVersion'] = $GLOBALS['AKB_DB']->FetchOne("SELECT VERSION()");
		}
	}

	// Initialise our Ldap Class
	if ( isset($GLOBALS['ldapEnabled']) && $GLOBALS['ldapEnabled'] ) {
		// Construct the structure of the user details mapping
		API_LDAP::constructUserDetailsMapping();

		// Initialize our LDAP class
		$GLOBALS['AKB_LDAP'] = LdapFactory::initializeLdap($GLOBALS['ldapUserAccountType'], $GLOBALS['ldapHost'], $GLOBALS['ldapPort'], $GLOBALS['ldapConnectUsername'], $GLOBALS['ldapConnectPassword'], $GLOBALS['ldapBaseDn'], $GLOBALS['ldapVersionThree'], $GLOBALS['ldapNegoTLS'], $GLOBALS['ldapFollowReferral']);
	}
	
	// Variable for Search Library
	$GLOBALS["FF_CFG"]["site"]["indexSubDomains"] = false;
	$GLOBALS['FF_CFG']['site']['indexExtensions'] = '';
	$GLOBALS['FF_CFG']['site']['ignoreQueryStrings'] = '';
	if (isset($GLOBALS["pathToKB"]) && $GLOBALS["pathToKB"]) {
		$GLOBALS["FF_CFG"]["site"]["siteURL"] = $GLOBALS["pathToKB"];
	}
	
	// Variable for temp directory
	if (isset($GLOBALS['tempDirectory']) && $GLOBALS['tempDirectory'] != '') {
		define('TEMP_DIRECTORY', $GLOBALS['tempDirectory']);
	} else {
		define('TEMP_DIRECTORY', '/tmp');
	}
	// Init the available document plugins.
	$GLOBALS['DocumentPlugins'] = array('Default_Plugin','External_Doc_Plugin','Docx_Plugin','External_Ppt_Plugin','Pdf_Plugin','Image_Plugin');
	
	// Init current Datetime.
	$GLOBALS['currDatetime'] = date('Y-m-d H:i:s');
	
	// Init the login security
	$GLOBALS['enabledLoginSecurity'] = false;
	if (isset($GLOBALS['bannedRetried']) && isset($GLOBALS['bannedPeriod']) && is_numeric($GLOBALS['bannedRetried']) &&  is_numeric($GLOBALS['bannedPeriod'])) {
		$GLOBALS['enabledLoginSecurity'] = true;
	}
	
	// If magic_quotes_gpc is on, strip all the slashes it added. By doing
	// this we can be sure that all the gpc vars never have slashes and so
	// we will always need to treat them the same way
	if (get_magic_quotes_gpc()) {
		$_POST		= stripslashes_deep($_POST);
		$_GET		= stripslashes_deep($_GET);
		$_COOKIE	= stripslashes_deep($_COOKIE);
		$_REQUEST	= stripslashes_deep($_REQUEST);
	}

	//Remote Constants
	define('ADMIN_TABLE_REMOTE_URL',$GLOBALS['pathToKB'].'/admin/remote/remote_admin_table.php');
	define('LOGGED_OUT_JS','<script language="javascript">JSLoggedOut();</script>');

	$valid_charsets = Array (
		'utf-8',
		'iso-8859-1',
	);

	if (!isset($GLOBALS['charset']) || !in_array($GLOBALS['charset'], $valid_charsets)) {
		$GLOBALS['charset'] = 'iso-8859-1';
	}
	header('Content-type: text/html; charset='.$GLOBALS['charset']);

	if (isset($GLOBALS['rightToLeft']) && $GLOBALS['rightToLeft']) {
		$GLOBALS['RTL_HTML'] = ' dir="rtl"';
	} else {
		$GLOBALS['RTL_HTML'] = '';
	}
	
	//Attempt to set the cookie path.
	$pArray = explode("/",$GLOBALS["pathToKB"]);
	$cookiePath = "/";
	for ($i=3;$i<count($pArray);$i++) {
		$cookiePath .= $pArray[$i]."/";
	}

	session_set_cookie_params(0,$cookiePath);

	//Init Inline Help
	if (isInlineHelp()) {
		$GLOBALS['template'] = "InlineHelp";
		$GLOBALS['InlineHelp'] = true;
		$GLOBALS['cleanUrls'] = false;
		$GLOBALS['InlineHelpHeader'] = htmlentities($_GET['tplHeader']);
	}
	
	

	//Start the session
	session_start();

?>
